package cn.wolfcode.luowowo2.website.web.interceptor;

import cn.wolfcode.luowowo2.cache.prefix.UserInfoKeyPrefix;
import cn.wolfcode.luowowo2.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo2.member.domain.UserInfo;
import cn.wolfcode.luowowo2.util.CookieUtil;

import cn.wolfcode.luowowo2.website.web.annotation.RequireLogin;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by Albert on 2019/7/8.
 */
public class CheckLoginInterceptor implements HandlerInterceptor{
    @Reference
    private IUserInfoRedisService userInfoRedisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Cookie cookie = CookieUtil.getCookie(request, UserInfoKeyPrefix.USER_INFO_TOKEN_COOKIE_NAME);

        UserInfo userInfo= null;

        if(cookie != null){
            userInfo = userInfoRedisService.getUserInfoByToken(UserInfoKeyPrefix.USER_INFO_TOKEN, cookie.getValue());
        }

        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            //其实可以使用handlerMethod.hasMethodAnnotation(RequireLogin.class)
            RequireLogin methodAnnotation = handlerMethod.getMethodAnnotation(RequireLogin.class);
            if (methodAnnotation!=null) {
                if(userInfo == null){
                    response.sendRedirect("/login.html");
                    return false;
                }

            }

        }
        return true;
    }
}
